// pages/payMethod/payMethod.js
const orderService = require('../../../../api/orderService.js')
const memberService = require('../../../../api/memberService.js')
const advanceSellService = require('../../../../api/advanceSellService.js')
const redPacketService = require('../../../../api/redPacketService.js')
const utils = require('../../../../utils/utils.js')

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentItem: -1,
    balance: 0,
    order: {
      id: '',
      cashTotal: 0
    },
    password: '',
    type: 'normal',
    from: 'shopCart',
    modal: false,
    focus: false,
    orderPay: false,
    canBuy: false,
    cardPay: false,
    payments: {
      cardPay: {
        total: 0
      },
      wxPay: {
        total: 0
      }
    },
    show: {
      middle: false,
      top: false,
      bottom: false,
      right: false,
      right2: false
    },
  },
  // 重置密码
  handleResetPassword: function () {
    wx.navigateTo({
      url: '../../order/resetPassword/resetPassword'
    })
  },
  // 处理储值卡密码
  handlePassword: function (e) {
    if (e.detail.value) {
      this.setData({
        password: e.detail.value
      })
    }
  },
  clickBlank: function () {
    this.setData({
      modal: false
    })
  },

  clickBody: function () {

  },

  // 储值余额支付方式点击
  cardPayClick: function () {
    const that = this
    if (!this.data.cardPay) {
      if (this.data.balance > 0) {
        this.setData({
          modal: true
        })
      } else {
        this.setData({
          'payments.cardPay.total': 0,
          cardPay: true,
          password: '',
        })
        if (that.data.currentItem !== 1) {
          that.setData({
            canBuy: false
          })
        }
      }
    } else {
      this.setData({
        'payments.cardPay.total': 0,
        cardPay: false,
        password: ''
      })
    }
  },

  // 点击支付方式
  payClick: function (val) {
    var that = this
    var id = val.currentTarget.dataset.id;
    const type = that.data.type
    console.log(id)
    //设置当前样式
    if (type !== 'payTail') {
      if (that.data.currentItem === id) {
        that.setData({
          currentItem: -1
        })
      } else {
        that.setData({
          currentItem: id,
          canBuy: true
        })
      }
    } else {
      // 预收付款
      if (that.data.currentItem === id) {
        that.setData({
          currentItem: -1
        })
      } else {
        if (id !== 0) {
          that.setData({
            currentItem: id,
            canBuy: true
          })
        } else {
          wx.showToast({
            title: '预售订单暂不支持储值余额支付尾款~',
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
  },
  // 获取订单信息和储值余额
  getOrderDataById: function (id) {
    orderService.getDetailsById(id).then(res => {
      console.log(res)
      let tempData = {
        ...res
      }
      this.setData({
        order: tempData
      })
      // if (this.data.balance < res.cashTotal) {
      //   this.setData({
      //     currentItem: 1
      //   })
      // }
      return memberService.getMbrBalance()
    }).then(balance => {
      this.setData({
        balance: balance
      })
    }).catch(e => {
      console.log(e.message)
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 支付订单
   */
  toPayment: function () {
    const that = this
    const order = this.data.order
    const type = that.data.type
    const from = that.data.from
    if (this.data.canBuy) {
      this.setData({
        canBuy: false
      })
      // 判断是正常订单还是支付尾款
      if (type === 'normal') {
        if (that.data.cardPay) {
          if (that.data.payments.cardPay.total == order.cashTotal) {
            that.getCardPay(order)
          } else {
            if (that.data.currentItem === 1) {
              if (that.data.payments.cardPay.total > 0) {
                that.getPay(order)
              } else {
                that.getWXPay(order)
              }
            } else {
              that.setData({
                canBuy: false
              })
              wx.showToast({
                title: '请选择支付方式~',
                icon: 'none',
                duration: 2000
              })
            }
          }
        } else {
          if (that.data.currentItem === 1) {
            that.getWXPay(order)
          } else {
            that.setData({
              canBuy: false
            })
            wx.showToast({
              title: '请选择支付方式~',
              icon: 'none',
              duration: 2000
            })
          }
        }
      } else if (type === 'payTail') {
        if (that.data.cardPay) {
          that.setData({
            canBuy: false
          })
          wx.showToast({
            title: '预售订单暂不支持储值余额支付尾款~',
            icon: 'none',
            duration: 2000
          })
        } else if (that.data.currentItem === 1) {
          that.toPayTail(order)
        } else {
          that.setData({
            canBuy: false
          })
          wx.showToast({
            title: '请选择支付方式~',
            icon: 'none',
            duration: 2000
          })
        }
      } else {
        if (that.data.cardPay) {
          if (that.data.payments.cardPay.total == order.cashTotal) {
            that.cardPay(order)
          } else {
            if (that.data.currentItem === 1) {
              if (that.data.payments.cardPay.total > 0) {
                that.getPay(order)
              } else {
                that.getWXPay(order)
              }
            } else {
              that.setData({
                canBuy: false
              })
              wx.showToast({
                title: '请选择支付方式~',
                icon: 'none',
                duration: 2000
              })
            }
          }
        } else {
          if (that.data.currentItem === 1) {
            that.getWXPay(order)
          } else {
            that.setData({
              canBuy: false
            })
            wx.showToast({
              title: '请选择支付方式~',
              icon: 'none',
              duration: 2000
            })
          }
        }
      }
    } else {
      if (that.data.currentItem === -1 && !that.data.cardPay) {
        wx.showToast({
          title: '请选择支付方式~',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
  // 微信支付
  getWXPay: function (order) {
    const self = this
    let tempData = {
      orderId: order.id,
      // payMethod: 'SWIFTPASS'
      payMethod: 'WX_MINI_APP'
    }
    if (order.cashTotal === 0) {
      self.toPaymentSuccess(order.id)
    } else {
      orderService.getPaySign(tempData).then(res => {
        var resData = JSON.parse(res);
        var sign = JSON.parse(resData.sign)
        // console.log(resData)
        console.log(sign)
        console.log(sign.paySign)
        let packageValue = ''
        if (tempData.payMethod === 'SWIFTPASS') {
          packageValue = sign.package
        } else if (tempData.payMethod === 'WX_MINI_APP') {
          packageValue = sign.packageValue
        }
        wx.requestPayment({
          'timeStamp': sign.timeStamp,
          'nonceStr': sign.nonceStr,
          'package': packageValue,
          'signType': sign.signType,
          'paySign': sign.paySign,
          'success': function (res) {
            let orderId = tempData.orderId
            let amount = 0
            var selfTime = setInterval(function () {
              orderService.getOrderStatusById(orderId).then(result => {
                console.log('查询交易结果-------------')
                console.log(result)
                if (result.status === 'PAID') {
                  utils.setHideLoading(false);
                  clearInterval(selfTime)
                  wx.showToast({
                    title: '支付成功',
                    icon: 'none',
                    duration: 2000
                  })
                  self.toPaymentSuccess(orderId)
                } else if (result.status === 'WAITPAYBALANCE') {
                  utils.setHideLoading(false);
                  // 待付尾款
                  clearInterval(selfTime)
                  wx.showToast({
                    title: '支付成功',
                    icon: 'none',
                    duration: 2000
                  })
                  self.toPaymentSuccess(orderId)
                } else if (result.status === 'PENDING') {
                  utils.setHideLoading(false);
                  // 待自提
                  clearInterval(selfTime)
                  wx.showToast({
                    title: '支付成功',
                    icon: 'none',
                    duration: 2000
                  })
                  self.toPaymentSuccess(orderId)
                } else {
                  utils.setHideLoading(true);
                }
                amount++
                if (amount > 40) {
                  utils.setHideLoading(false);
                  clearInterval(selfTime)
                  self.toggle('middle');
                }
              }).catch(err => {
                clearInterval(selfTime)
                self.toggle('middle');
                wx.showToast({
                  title: err.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              })
            }, 500)
          },
          'fail': function (res) {
            console.log('支付失败')
            console.log(res)
            self.setData({
              canBuy: true
            })
            if (res.errMsg === 'requestPayment:fail cancel') {
              wx.showToast({
                title: '您取消了支付订单~',
                icon: 'none',
                duration: 2000
              })
              wx.switchTab({
                url: '../../goods/shopcart/shopcart'
              })
            } else {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
              wx.switchTab({
                url: '../../goods/shopcart/shopcart'
              })
            }
          }
        })
      }).catch(err => {
        if (err.code === -1001) {
          // 请求超时
          if (self.data.cardPay === true && self.data.payments.cardPay.total > 0) {
            self.orderLock(order)
          }
          self.toggle('middle');
        } else {
          self.setData({
            canBuy: true
          })
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  // 微信支付
  getPay: function (order) {
    const self = this
    let tempData = {
      orderId: order.id,
      // payMethod: 'SWIFTPASS'
      payMethod: 'WX_MINI_APP'
    }
    if (order.cashTotal === 0) {
      self.toPaymentSuccess(order.id)
    } else {
      let postData = {
        orderId: order.id,
        cardAmount: self.data.payments.cardPay.total
      }
      let password = this.data.password
      if (password !== '') {
        postData = {
          ...postData,
          password: password
        }
      }
      orderService.prepareCardPay(postData).then(res => {
        console.log(res)
        return orderService.getPaySign(tempData)
      }).then(res => {
        var resData = JSON.parse(res);
        var sign = JSON.parse(resData.sign)
        // console.log(resData)
        console.log(sign)
        console.log(sign.paySign)
        let packageValue = ''
        if (tempData.payMethod === 'SWIFTPASS') {
          packageValue = sign.package
        } else if (tempData.payMethod === 'WX_MINI_APP') {
          packageValue = sign.packageValue
        }
        wx.requestPayment({
          'timeStamp': sign.timeStamp,
          'nonceStr': sign.nonceStr,
          'package': packageValue,
          'signType': sign.signType,
          'paySign': sign.paySign,
          'success': function (res) {
            let orderId = tempData.orderId
            let amount = 0
            var selfTime = setInterval(function () {
              orderService.getOrderStatusById(orderId).then(result => {
                console.log('查询交易结果-------------')
                console.log(result)
                if (result.status === 'PAID') {
                  utils.setHideLoading(false);
                  clearInterval(selfTime)
                  wx.showToast({
                    title: '支付成功',
                    icon: 'none',
                    duration: 2000
                  })
                  self.toPaymentSuccess(orderId)
                } else if (result.status === 'WAITPAYBALANCE') {
                  utils.setHideLoading(false);
                  // 待付尾款
                  clearInterval(selfTime)
                  wx.showToast({
                    title: '支付成功',
                    icon: 'none',
                    duration: 2000
                  })
                  self.toPaymentSuccess(orderId)
                } else if (result.status === 'PENDING') {
                  utils.setHideLoading(false);
                  // 待自提
                  clearInterval(selfTime)
                  wx.showToast({
                    title: '支付成功',
                    icon: 'none',
                    duration: 2000
                  })
                  self.toPaymentSuccess(orderId)
                } else {
                  utils.setHideLoading(true);
                }
                amount++
                if (amount > 40) {
                  utils.setHideLoading(false);
                  clearInterval(selfTime)
                  self.toggle('middle');
                }
              }).catch(err => {
                clearInterval(selfTime)
                self.toggle('middle');
                wx.showToast({
                  title: err.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              })
            }, 500)
          },
          'fail': function (res) {
            console.log('支付失败')
            console.log(res)
            self.setData({
              canBuy: true
            })
            if (res.errMsg === 'requestPayment:fail cancel') {
              wx.showToast({
                title: '您取消了支付订单~',
                icon: 'none',
                duration: 2000
              })
              wx.switchTab({
                url: '../../goods/shopcart/shopcart'
              })
            } else {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
              wx.switchTab({
                url: '../../goods/shopcart/shopcart'
              })
            }
          }
        })
      }).catch(err => {
        if (err.code === -1001) {
          // 请求超时
          if (self.data.cardPay === true && self.data.payments.cardPay.total > 0) {
            self.orderLock(order)
          }
          self.toggle('middle');
        } else {
          self.setData({
            canBuy: true
          })
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  // 储值卡支付
  toCardPay: function () {
    const order = this.data.order
    if (this.data.password !== '') {
      // this.cardPay(order)
      if (this.data.balance > order.cashTotal) {
        this.setData({
          'payments.cardPay.total': order.cashTotal,
          canBuy: true
        })
      } else {
        this.setData({
          'payments.cardPay.total': this.data.balance
        })
      }
      this.setData({
        cardPay: true,
        modal: false
      })
    } else {
      wx.showToast({
        title: '请输入储值卡密码~',
        icon: 'none',
        duration: 2000
      })
      this.setData({
        focus: true
      })
    }
  },
  // 储值卡支付
  getCardPay: function (order) {
    const self = this
    let postData = {
      orderId: order.id
    }
    let password = this.data.password
    if (password !== '') {
      postData = {
        ...postData,
        password: password
      }
    }
    orderService.cardPay(postData).then(res => {
      console.log(res)
      let orderId = order.id
      let amount = 0
      var selfTime = setInterval(function () {
        orderService.getOrderStatusById(orderId).then(result => {
          console.log('查询交易结果-------------')
          console.log(result)
          if (result.status === 'PAID') {
            utils.setHideLoading(false);
            clearInterval(selfTime)
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              duration: 2000
            })
            self.toPaymentSuccess(orderId)
          } else if (result.status === 'PENDING') {
            utils.setHideLoading(false);
            // 待自提
            clearInterval(selfTime)
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              duration: 2000
            })
            self.toPaymentSuccess(orderId)
          } else {
            self.setData({
              canBuy: true
            })
            utils.setHideLoading(true);
          }
          amount++
          if (amount > 40) {
            utils.setHideLoading(false);
            clearInterval(selfTime)
            self.toggle('middle');
          }
        }).catch(err => {
          clearInterval(selfTime)
          self.toggle('middle');
          wx.showToast({
            title: err.errMsg,
            icon: 'none',
            duration: 2000
          })
        })
      }, 500)
    }).catch(e => {
      console.log(e.message)
      if (err.code === -1001) {
        // 请求超时
        self.orderLock(order)
        self.toggle('middle');
      } else {
        self.setData({
          canBuy: true
        })
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      }
    })
    // self.orderLock(order)
  },
  // 储值卡支付（支持混合支付）
  cardPay: function (order) {
    const self = this
    let postData = {
      orderId: order.id,
      cardAmount: self.data.payments.cardPay.total
    }
    let password = this.data.password
    if (password !== '') {
      postData = {
        ...postData,
        password: password
      }
    }
    orderService.prepareCardPay(postData).then(res => {
      console.log(res)
      let orderId = postData.orderId
      var selfTime = setInterval(function () {
        orderService.getOrderStatusById(orderId).then(result => {
          console.log('查询交易结果-------------')
          console.log(result)
          if (result.status === 'PAID') {
            utils.setHideLoading(false);
            clearInterval(selfTime)
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              duration: 2000
            })
            self.toPaymentSuccess(orderId)
          } else if (result.status === 'WAITPAYBALANCE') {
            utils.setHideLoading(false);
            // 待付尾款
            clearInterval(selfTime)
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              duration: 2000
            })
            self.toPaymentSuccess(orderId)
          } else if (result.status === 'PENDING') {
            utils.setHideLoading(false);
            // 待自提
            clearInterval(selfTime)
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              duration: 2000
            })
            self.toPaymentSuccess(orderId)
          } else {
            utils.setHideLoading(true);
          }
        }).catch(err => {
          clearInterval(selfTime)
          wx.showToast({
            title: err.errMsg,
            icon: 'none',
            duration: 2000
          })
        })
      }, 500)
    }).catch(err => {
      if (err.code === -1001) {
        // 请求超时
        self.orderLock(order)
        self.toggle('middle');
      } else {
        this.setData({
          canBuy: true
        })
        wx.showToast({
          title: err.message,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 订单上锁
  orderLock: function (order) {
    orderService.orderLock(order.id).then(res => {
      console.log(res)
    })
  },
  toPayTail: function (order) {
    const that = this
    let tempData = {
      orderId: this.data.order.id,
      // payMethod: 'SWIFTPASS'
      payMethod: 'WX_MINI_APP'
    }
    advanceSellService.getBalancePaySign(tempData).then(res => {
      console.log(res)
      var resData = JSON.parse(res);
      var sign = JSON.parse(resData.sign)
      let packageValue = ''
      if (tempData.payMethod === 'SWIFTPASS') {
        packageValue = sign.package
      } else if (tempData.payMethod === 'WX_MINI_APP') {
        packageValue = sign.packageValue
      }
      wx.requestPayment({
        'timeStamp': sign.timeStamp,
        'nonceStr': sign.nonceStr,
        'package': packageValue,
        'signType': sign.signType,
        'paySign': sign.paySign,
        'success': function (res) {
          let orderId = tempData.orderId
          var selfTime = setInterval(function () {
            orderService.getOrderStatusById(orderId).then(result => {
              console.log('查询交易结果-------------')
              console.log(result)
              if (result.status === 'PAID') {
                utils.setHideLoading(false);
                clearInterval(selfTime)
                wx.showToast({
                  title: '支付成功',
                  icon: 'none',
                  duration: 2000
                })
                self.toPaymentSuccess(orderId)
              } else if (result.status === 'WAITPAYBALANCE') {
                utils.setHideLoading(false);
                // 待付尾款
                clearInterval(selfTime)
                wx.showToast({
                  title: '支付成功',
                  icon: 'none',
                  duration: 2000
                })
                self.toPaymentSuccess(orderId)
              } else if (result.status === 'PENDING') {
                utils.setHideLoading(false);
                // 待自提
                clearInterval(selfTime)
                wx.showToast({
                  title: '支付成功',
                  icon: 'none',
                  duration: 2000
                })
                self.toPaymentSuccess(orderId)
              } else {
                utils.setHideLoading(true);
              }
            }).catch(err => {
              clearInterval(selfTime)
              wx.showToast({
                title: err.errMsg,
                icon: 'none',
                duration: 2000
              })
            })
          }, 500)
        },
        'fail': function (res) {
          console.log('支付失败')
          console.log(res)
          if (res.errMsg === 'requestPayment:fail cancel') {
            wx.showToast({
              title: '您取消了支付订单~',
              icon: 'none',
              duration: 2000
            })
            wx.switchTab({
              url: '../../goods/shopcart/shopcart'
            })
          } else {
            wx.showToast({
              title: res.errMsg,
              icon: 'none',
              duration: 2000
            })
            wx.switchTab({
              url: '../../goods/shopcart/shopcart'
            })
          }
        }
      })
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 支付成功
  toPaymentSuccess: function (orderId) {
    this.setData({
      orderPay: true
    })
    wx.navigateTo({
      url: '../../pay/payment/payment?orderId=' + orderId + '&from=' + this.options.from
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    console.log(options)
    this.setData({
      type: options.type,
      from: options.from
    })
    if (options.orderId) {
      this.getOrderDataById(options.orderId)
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("onHide")
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("onUnload")
    if (!this.data.orderPay) {
      if (this.options.from === 'shopCart') {
        wx.switchTab({
          url: '../../goods/shopcart/shopcart'
        })
      } else {

      }
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 打开弹窗
   */
  toggleMiddlePopup() {
    this.toggle('middle');
    this.setData({
      orderPay: true
    })
    wx.redirectTo({
      url: '../../order/order/order'
    })
  },
  toggle(type) {
    this.setData({
      [`show.${type}`]: !this.data.show[type]
    });
  }
})